import {Button, Card, Input, InputNumber, List, message, Modal, Space, Spin} from 'antd';
import {forwardRef, useEffect, useState} from "react";
import {
    addChapterEventAPI,
    getChapterEventAPI,
    addChapterCatalogAPI,
    updateChapterEventAPI, addBookContentAPI
} from "../../../../apis/novel.js";
import {useLocation} from "react-router-dom";
import {baseURL} from "../../../../utils/request.js";


const BriefIntroduction = forwardRef((props, ref) => {
    const location = useLocation();


    const [eventCount, setEventCount] = useState(5)

    //    情节事件
    const [events, setEvents] = useState([])


    // 查询章节事件
    const getChapterList = async (chapterId) => {
        let res = await getChapterEventAPI(location.state.novelInfo.bookId, chapterId)
        console.log('查询章节事件', res)
        if (res.code === '0000') {
            setEvents(res.data)
            message.success('查询章节事件成功')
            window.localStorage.setItem('events', JSON.stringify(res.data))
        } else {
            message.error(res.msg)
        }
    }

    useEffect(() => {
        getChapterList(window.localStorage.getItem('chapterId'))
    }, [])

    // 生成情节
    const generateStory = async () => {
        setIsgenerateLoading(true)

        let data = {
            bookId: location.state.novelInfo.bookId,
            detail: '',
            contentRequestEntities: [],
            model: window.localStorage.getItem('gpt'),
            eventCount: parseInt(eventCount),
            sort: window.localStorage.getItem('sort'),
            chapterId: window.localStorage.getItem('chapterId')
        }

        console.log('生成情节参数', data)

        let res = await addChapterEventAPI(data)
        console.log('生成情节', res)
        if (res.code === '0000') {
            if (JSON.stringify(res.data) === '[{}]') {
                message.error('生成情节失败，请重新生成')
                return
            }
            setEvents(res.data)
            message.success('生成情节成功,记得保存哦')
            setIsModalOpen(false)
        } else {
            message.error(res.msg || '生成情节失败，请重新生成')
        }
        setIsgenerateLoading(false)
    }

    useEffect(() => {
        generateStory()
    }, []);


    const [isModalOpen, setIsModalOpen] = useState(false);


    const handleCancel = () => {
        setIsModalOpen(false);
    };


    // 保存事件
    const saveEvent = async () => {
        let res = await getChapterEventAPI(location.state.novelInfo.bookId, window.localStorage.getItem('chapterId'))
        console.log('查询章节事件', res)
        if (res.data.length === 0) {
            let data = {
                bookId: location.state.novelInfo.bookId,
                chapterId: window.localStorage.getItem('chapterId'),
                events: events
            }
            let addRes = await addChapterCatalogAPI(data)
            console.log('保存新增情节', addRes)
            if (addRes.code === '0000') {
                message.success('保存成功')
                getChapterList(window.localStorage.getItem('chapterId'))
                window.localStorage.getItem('events', JSON.stringify(events))
            } else {
                message.error(addRes.msg)
            }
        } else if (res.data.length > 0) {
            let data = {
                bookId: location.state.novelInfo.bookId,
                chapterId: window.localStorage.getItem('chapterId'),
                events: events
            }

            let updateRes = await updateChapterEventAPI(data)

            console.log('update', updateRes)
            if (updateRes.code === '0000') {
                message.success('保存成功')
                getChapterList(window.localStorage.getItem('chapterId'))
                window.localStorage.getItem('events', JSON.stringify(events))
            } else {
                message.error(updateRes.msg)
            }
        }

    }


    // 生成内容方法
    const generateContent = async (index) => {
        let data = {
            events: JSON.parse(window.localStorage.getItem('events')),
            index,
            headline: window.localStorage.getItem('headline'),
            detail: '',
            model: window.localStorage.getItem('gpt')
        }


        const resp = await fetch(baseURL + '/api/v1/novel/gen/chapter/content/event', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                Authorization: window.localStorage.getItem('token'),
                // Authorization: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvb2lZWTZXMW1TUUpLYXFXVGxzd2hkYXdHeXBnIiwib3BlbklkIjoib29pWVk2VzFtU1FKS2FxV1Rsc3doZGF3R3lwZyIsImV4cCI6MTcxNDQ2MDkzMiwidXNlcklkIjoiMzY3NDQ2NDI3NTI3Mjg2Nzg0IiwiaWF0IjoxNzEzODU2MTMyLCJqdGkiOiI3ZmE3YjllZS1jZjlhLTQ5YzQtOWEzMS1mMWQzNGU5M2I3ZmEifQ.5eFcsrK62ASy8ecogKBTek6TgEQsn8pOjUcue9sGI90'
            },
            body: JSON.stringify(data)
        })

        const reader = resp.body.getReader()
        // let result =  resp.json()
        // console.log('11',result)
        let tempDrewContentData = ''
        const textDecoder = new TextDecoder()
        while (1) {
            const {done, value} = await reader.read()
            if (done) {
                break
            }
            const str = textDecoder.decode(value)
            console.log('简易文章', str)

            tempDrewContentData += str
            props.setContent(props.content + '\n' + tempDrewContentData)

        }


    }


    // 是否生成完成
    const [isgenerateLoading, setIsgenerateLoading] = useState(false)


    return (
        <>
            {/*生成事件数弹窗*/}

            <Modal title="想要生成多少个事件？" open={isModalOpen} okText={'开始生成'} cancelText={'取消'}
                   onOk={generateStory} onCancel={handleCancel}>
                <Spin spinning={isgenerateLoading}>
                    <InputNumber min={1} max={8} value={eventCount} onChange={(e) => {
                        //     修改eventCount
                        setEventCount(e)
                    }}/>
                </Spin>
            </Modal>
            <Card title={''} extra={<Space>
                <Button type={'primary'} onClick={setIsModalOpen}>生成情节</Button>
                <Button type={'primary'} onClick={saveEvent}>保存</Button>
            </Space>}>
                <List
                    itemLayout="horizontal"
                    dataSource={events}
                    renderItem={(item, index) => (
                        <List.Item>
                            <List.Item.Meta
                                title={<span>{item.headline}</span>}
                                description={item.topic}
                            />
                            <Button type={'primary'} onClick={() => generateContent(index)}>生成</Button>
                        </List.Item>
                    )}
                />
            </Card>


        </>
    )
})

export default BriefIntroduction